import {
  OrbitControls,
  useGLTF,
  useTexture,
  Center,
  Sparkles,
  shaderMaterial,
} from '@react-three/drei'
import * as THREE from 'three'
import { extend, useFrame } from '@react-three/fiber'
import VERTEXSHADER from './shader/vertex.glsl'
import FRAGMENTSHADER from './shader/fragment.glsl'
import { useRef } from 'react'

const PortalMaterial = shaderMaterial(
  {
    uTime: 0,
    uColorStart: new THREE.Color('#ffffff'),
    uColorEnd: new THREE.Color('#000000'),
  },
  VERTEXSHADER,
  FRAGMENTSHADER
)
extend({ PortalMaterial })

const Expercise = () => {
  const { nodes } = useGLTF('/portal/portal.glb')
  const bakedMap = useTexture('/portal/baked.jpg')
  bakedMap.flipY = false
  console.log(nodes, 'mode;')
  const portalRef = useRef<THREE.ShaderMaterial>(null!)
  useFrame(({ clock }) => {
    const time = clock.elapsedTime
    portalRef.current.uTime = time
  })
  return (
    <>
      <color args={['#030202']} attach="background" />
      <OrbitControls />

      <Center>
        <mesh geometry={nodes.baked.geometry}>
          <meshBasicMaterial map={bakedMap} />
        </mesh>
        <mesh
          geometry={nodes.poleLightA.geometry}
          position={nodes.poleLightA.position}
        >
          <meshBasicMaterial color="#ffffe5" />
        </mesh>
        <mesh
          geometry={nodes.poleLightB.geometry}
          position={nodes.poleLightB.position}
        ></mesh>
        <mesh
          geometry={nodes.portalLight.geometry}
          position={nodes.portalLight.position}
          rotation={nodes.portalLight.rotation}
        >
          <portalMaterial ref={portalRef} />
        </mesh>
        <Sparkles
          count={30}
          scale={[4, 2, 4]}
          size={6}
          position-y={1}
          speed={0.3}
        />
      </Center>
    </>
  )
}

export default Expercise
